﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using IMMotors;
using UnityEngine.SceneManagement;

public class RoomScene : MonoBehaviour
{
    public GameObject PopUpCrossPromotion;
    public GameObject PopUpPause;
    public GameObject PopUpLevelCompleted;
    public GameObject PopUpLevelFailed;
    public GameObject PopUpWatchVideoForTime;
    public GameObject PopUpVideoNotAvailable;
    public GameObject PopUpWIN;

    public MenuManager menuManager;

    public static bool bTaskAnim = false;

    public Sprite SoundOn;
    public Sprite SoundOff;
    public Image BtnSoundIcon;

    public Image BtnMenuBG;
    public Animator animMoreOptionsMenu;

    public static bool bPause = true;
    public static bool bMoreOptionsMenu = false;

    public CanvasGroup BlockAll;
    public CanvasGroup HintBg;
    public Image LevelBg;

    public Animator animTasks;
    public Text txtAllTasks;
    public Text txtCompletedTasks;
    public Text txtHintsLeft;
    public Image imgHintsLeft;
    public Sprite imgHintsLeftOff;
    public Sprite[] hintsLeft;
    public Button btnHintsLeft;
    int videoBonusHints = 0;
    int videoBonusTime = 0;

    public static int selectedRoom = 1;

    List<SpriteRenderer> HintSprites = new List<SpriteRenderer>();

    ToolType[] tools = new ToolType[] { ToolType.none, ToolType.none, ToolType.none };
    public static int[] ToolActionsLeft = new int[] { 0, 0, 0 };
    bool bHintActivated = false;
    bool bVideoBonusHintActivated = false;
    string menuWatchVideoName = "";

    public ParticlesController psController;

    void Awake()
    {
        bTaskAnim = false;
        float scaleBg = 1 - 0.07f * (16f / 9f - (float)Screen.width / (float)Screen.height); //0.09f
        LevelBg.transform.parent.localScale = scaleBg * Vector3.one;
        HintBg.transform.localScale = scaleBg * Vector3.one;
    }

    async void Start()
    {
        GameData.bWatchVideoReady = false;
        GameData.bWatchVideoStart = false;
        Input.multiTouchEnabled = false;

        if (SoundManager.soundOn == 0)
            BtnSoundIcon.sprite = SoundOff;
        else
            BtnSoundIcon.sprite = SoundOn;

        bMoreOptionsMenu = false;
        GameData.Init();

        if (GameData.TutorialShown == 0 || GameData.TestTutorial)
        {
            //GameData.TutorialShown = 0;
//			Debug.Log ("TEST TUT");
            transform.GetComponent<Tutorial>().enabled = true;
            Tutorial.bTutorial = true;
        }
        else
        {
            transform.GetComponent<Tutorial>().DestroyTut();
            Tutorial.bTutorial = false;
        }

        HintBg.gameObject.SetActive(true);

        ToolActionsLeft = new int[] { 0, 0, 0 };

        GameData.CurrentLevel = selectedRoom;
        GameData.TotalTasks = 0;
        GameData.CompletedTasks = 0;

        bPause = true;
        StartCoroutine("WaitStart");
        GameData.SetNewLevel();
        txtCompletedTasks.text = "0";

        imgHintsLeft.sprite = hintsLeft[GameData.HintsLeft];

        //ucitavanje pozadine
        // Sprite BG = Instantiate(Resources.Load("BGCompressed/Room" + selectedRoom.ToString(),
        //     typeof(Sprite))) as Sprite;
        Sprite BG = await AAMgr.Instance.LoadAssetAsync<Sprite>($"Room{selectedRoom}");
        HintBg.transform.Find("BG").GetComponent<Image>().sprite = BG;
        HintBg.transform.Find("BG").GetComponent<Image>().enabled = true;
        LevelBg.sprite = BG;

        for (int i = HintBg.transform.childCount - 1; i >= 0; i--)
        {
            if (HintBg.transform.GetChild(i).name != "Room" + selectedRoom.ToString() &&
                LevelBg.transform.parent.GetChild(i).name != "BG")
            {
                GameObject.Destroy(HintBg.transform.GetChild(i).gameObject);
            }
            else HintBg.transform.GetChild(i).gameObject.SetActive(true);
        }

        for (int i = LevelBg.transform.parent.childCount - 1; i >= 0; i--)
        {
            if (LevelBg.transform.parent.GetChild(i).name != "Room" + selectedRoom.ToString() &&
                LevelBg.transform.parent.GetChild(i).name != "BG")
            {
                GameObject.Destroy(LevelBg.transform.parent.GetChild(i).gameObject);
            }
            else LevelBg.transform.parent.GetChild(i).gameObject.SetActive(true);
        }

        if (selectedRoom == 1)
        {
            LevelBg.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -50);
            HintBg.transform.Find("BG").GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -50);
        }
        else if (selectedRoom == 2)
        {
            LevelBg.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -20);
            HintBg.transform.Find("BG").GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -20);
        }
        else if (selectedRoom == 3)
        {
            LevelBg.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -30);
            HintBg.transform.Find("BG").GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -30);
        }
        else if (selectedRoom == 4)
        {
            LevelBg.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 58);
            HintBg.transform.Find("BG").GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 58);
        }
        else if (selectedRoom == 5)
        {
            LevelBg.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
            HintBg.transform.Find("BG").GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
        }
        else if (selectedRoom == 6)
        {
            LevelBg.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -30);
            HintBg.transform.Find("BG").GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -30);
        }
        else if (selectedRoom == 7)
        {
            LevelBg.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -40);
            HintBg.transform.Find("BG").GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -40);
        }
        else if (selectedRoom == 8)
        {
            LevelBg.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 58);
            HintBg.transform.Find("BG").GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 58);
        }

        //brisi
        GameObject[] anch = GameObject.FindGameObjectsWithTag("ANCHOR");

        foreach (GameObject a in anch)
        {
            for (int i = 0; i < a.transform.childCount; i++)
            {
                GameObject.Destroy(a.transform.GetChild(i).gameObject);
            }
        }

        CreateTools();
        CreateItems();
    }

    async void CreateTools()
    {
        tools = CleaningTool.ReturnRoomTools(selectedRoom);

        //TODO: sredi automatsko kreiranje alata

        // GameObject tool1 = Instantiate(Resources.Load("Prefabs/Tools/Duster", typeof(GameObject))) as GameObject;
        // tool1.transform.SetParent(GameObject.Find("Tool01Mask").transform);
        GameObject tool1 = await AAMgr.Instance.InstantiateAsync("Duster", GameObject.Find("Tool01Mask").transform);
        tool1.transform.localScale = Vector3.one;
        tool1.GetComponent<CleaningTool>().ToolNo = 1;

        // GameObject tool2 = Instantiate(Resources.Load("Prefabs/Tools/Brush", typeof(GameObject))) as GameObject;
        // tool2.transform.SetParent(GameObject.Find("Tool02Mask").transform);
        GameObject tool2 = await AAMgr.Instance.InstantiateAsync("Brush", GameObject.Find("Tool02Mask").transform);
        tool2.transform.localScale = Vector3.one;
        tool2.GetComponent<CleaningTool>().ToolNo = 2;

        // GameObject tool3 = Instantiate(Resources.Load("Prefabs/Tools/Sponge", typeof(GameObject))) as GameObject;
        // tool3.transform.SetParent(GameObject.Find("Tool03Mask").transform);
        GameObject tool3 = await AAMgr.Instance.InstantiateAsync("Sponge", GameObject.Find("Tool03Mask").transform);
        tool3.transform.localScale = Vector3.one;
        tool3.GetComponent<CleaningTool>().ToolNo = 3;
    }

    async void CreateItems()
    {
        HintSprites.Clear();
        Transform tr = GameObject.Find("TopLeftBorder").transform;

        Item.TopBorder = tr.position.y;
        Item.LeftBorder = tr.position.x;

        ItemsData.Init(selectedRoom);

        foreach (KeyValuePair<string, ItemData> kvp in ItemsData.ActiveRoom)
        {
            GameData.TotalTasks++;
            Debug.Log(kvp.Key.Split('*')[0]);
            // GameObject go =
            //     Instantiate(Resources.Load("Items/Room" + selectedRoom.ToString() + "/" + kvp.Key.Split('*')[0],
            //         typeof(GameObject))) as GameObject;
            GameObject go = await AAMgr.Instance.InstantiateAsync($"Room{selectedRoom}/{kvp.Key.Split('*')[0]}.prefab");
            string[] startAnchors = kvp.Value.START_POS_ANCHORS.Split(';');

            go.transform.parent = GameObject.Find("ImageBG/Room" + selectedRoom.ToString() + "/" +
                                                  startAnchors[Mathf.FloorToInt(Random.Range(0, startAnchors.Length))])
                .transform;
            go.transform.parent.localScale = Vector3.one;
            go.transform.localPosition = Vector3.zero;

            go.transform.localScale = new Vector3(kvp.Value.SCALE.x, kvp.Value.SCALE.y, 1);
            go.transform.Rotate(new Vector3(0, 0, kvp.Value.START_ROT));

            Item item = go.GetComponent<Item>();

            item.itemActionType = kvp.Value.ACTION;
            item.startRotation = kvp.Value.START_ROT;
            item.endRotation = (kvp.Value.END_ROT == -999) ? kvp.Value.START_ROT : kvp.Value.END_ROT;
            item.endScaleFactor = kvp.Value.END_SCALE_FACTOR;
            go.name = kvp.Key.Split('*')[0]; //  kvp.Key;
            item.itemHolder = kvp.Value.ITEM_HOLDER;
            item.destroyWithItemHolder = kvp.Value.DESTROY_WITH_I_H;
            item.DepnedentItemsList = kvp.Value.ITEMS_LIST;

            item.StartPosition = go.transform.position;
            if (kvp.Value.ACTION == ItemActionType.move || kvp.Value.ACTION == ItemActionType.moveAndChangeSprite ||
                kvp.Value.ACTION == ItemActionType.changeSprite)
            {
                item.EndPosition = GameObject
                    .Find("ImageBG/Room" + selectedRoom.ToString() + "/" + kvp.Value.END_POS_ANCHOR).transform;

                if (kvp.Value.END_POS_ANCHOR2 != "")
                {
//					Debug.Log("TRAZI ALT  "+kvp.Value.END_POS_ANCHOR2);
                    string[] AltEndPosNames = kvp.Value.END_POS_ANCHOR2.Split(new char[] { ';' },
                        System.StringSplitOptions.RemoveEmptyEntries);
                    item.alternativeEndPositions = new Transform[AltEndPosNames.Length];
                    for (int i = 0; i < AltEndPosNames.Length; i++)
                    {
                        item.alternativeEndPositions[i] = GameObject
                            .Find("ImageBG/Room" + selectedRoom.ToString() + "/" + AltEndPosNames[i]).transform;
//						Debug.Log("ALT  "+item.alternativeEndPositions [i].name);
                    }
                }

                item.alternativePrefabsName = kvp.Value.PREFAB2;
            }


            if (kvp.Value.ACTION == ItemActionType.clean)
            {
                for (int i = 0; i < tools.Length; i++)
                {
                    if (tools[i] == kvp.Value.TOOL)
                    {
                        go.layer = LayerMask.NameToLayer("Tool" + (i + 1).ToString() + "Interact");
                        ToolActionsLeft[i]++;
                    }
                }

                go.transform.parent.position += new Vector3(0, 0, 0.1f);
            }

            //************************************************************************************************************************
            //PRIKAZ POMOCI
            if ((kvp.Value.ACTION == ItemActionType.move && !kvp.Value.DESTROY_WITH_I_H) ||
                (kvp.Value.ACTION == ItemActionType.moveAndChangeSprite && !kvp.Value.DESTROY_WITH_I_H)
                || kvp.Value.ACTION == ItemActionType.changeSprite || kvp.Value.ACTION == ItemActionType.rotate)
            {
                string _name = go.name.Replace("_A", "_B");
                // GameObject goHlp =
                //     Instantiate(
                //         Resources.Load("Items/Room" + selectedRoom.ToString() + "/" + _name,
                //             typeof(GameObject))) as GameObject;
                GameObject goHlp =
                    await AAMgr.Instance.InstantiateAsync($"Room{selectedRoom}/{_name}.prefab");
                goHlp.name = "HLP_" + _name;


                if (kvp.Value.ACTION == ItemActionType.rotate)
                    goHlp.transform.parent = GameObject
                        .Find("HelpImageBG/Room" + selectedRoom.ToString() + "/" + go.transform.parent.name).transform;
                else
                    goHlp.transform.parent = GameObject
                        .Find("HelpImageBG/Room" + selectedRoom.ToString() + "/" + item.EndPosition.name).transform;

                goHlp.transform.parent.localScale = Vector3.one;
                goHlp.transform.localPosition = Vector3.zero;

                goHlp.transform.localScale =
                    new Vector3(kvp.Value.SCALE.x, kvp.Value.SCALE.y, 1) * kvp.Value.END_SCALE_FACTOR;
                ;
                goHlp.transform.Rotate(new Vector3(0, 0,
                    (kvp.Value.END_ROT == -999) ? kvp.Value.START_ROT : kvp.Value.END_ROT));

                goHlp.transform.GetComponent<Renderer>().sortingLayerName = "HINT";
                HintSprites.Add(goHlp.GetComponent<SpriteRenderer>());

                if (goHlp.transform.name == "HLP_Chandelier" && goHlp.transform.childCount > 0 &&
                    goHlp.transform.GetChild(0).name == "Chandelier")
                {
                    Debug.Log("SP SL");
                    goHlp.transform.GetChild(0).GetComponent<Renderer>().sortingLayerName = "HINT";
                    HintSprites.Add(goHlp.transform.GetChild(0).GetComponent<SpriteRenderer>());
                }

                goHlp.GetComponent<Collider2D>().enabled = false;
                goHlp.GetComponent<Item>().enabled = false;
            }

            //*************************************************************************************************************************
        }

        //StartCoroutine("FadeOutHint");
        FadeOutHint2();

        txtAllTasks.text = GameData.TotalTasks.ToString();
        txtCompletedTasks.text = "0";
    }

    IEnumerator WaitStart()
    {
        //StartCoroutine(SetBlockAll(0f,true));
        //StartCoroutine(SetBlockAll(2,false));
        yield return new WaitForSeconds(2);
        bPause = false;
    }


    public void btnSoundClick()
    {
        if (SoundManager.soundOn == 0)
        {
            SoundManager.Instance.SetSound(true);
            BtnSoundIcon.sprite = SoundOn;
        }
        else
        {
            SoundManager.Instance.SetSound(false);
            BtnSoundIcon.sprite = SoundOff;
        }

        SoundManager.Instance.Play_ButtonClick();
    }

    public void btnPauseClick()
    {
        if (bPause || Tutorial.bTutorial || bTaskAnim || GameData.CompletedTasks == GameData.TotalTasks) return;
        //WebelinxCMS.Instance.IsInterstitialAvailable(WebelinxCMS.INTERSTITIAL_MENI_ID);
        //Debug.Log("MENI INTERSTITAL, ID=" +WebelinxCMS.INTERSTITIAL_MENI_ID);

        bPause = true;
        if (bMoreOptionsMenu) btnMenuClick();
        if (bPause)
        {
            BlockAll.blocksRaycasts = true;
            StartCoroutine(SetBlockAll(GameData.AnimationInactiveTime, false));
            menuManager.ShowPopUpMenu(PopUpPause);
        }
    }

    public void btnResumeGameClick()
    {
        SoundManager.Instance.Play_ButtonClick();
        StartCoroutine(DelayPause());
        menuManager.ClosePopUpMenu(PopUpPause);
        BlockAll.blocksRaycasts = true;
        StartCoroutine(SetBlockAll(GameData.AnimationInactiveTime, false));
    }

    public void btnMoreAppsClick()
    {
        if (Tutorial.bTutorial || bTaskAnim || GameData.CompletedTasks == GameData.TotalTasks) return;
        bPause = true;
        SoundManager.Instance.Play_ButtonClick();
        menuManager.ShowPopUpMenu(PopUpCrossPromotion);
        EscapeButtonManager.AddEscapeButonFunction("btnCloseMoreAppsClick");
    }

    public void btnCloseMoreAppsClick()
    {
        Debug.Log(EscapeButtonManager.EscapeButonFunctionStack.Peek());
        StartCoroutine(DelayPause());
        SoundManager.Instance.Play_ButtonClick();
        menuManager.ClosePopUpMenu(PopUpCrossPromotion);
    }

    public void btnHomeClick()
    {
        AdsManager.Instance.ShowInterstitial();

        transform.SendMessage("StopTimer");
        SoundManager.Instance.Play_ButtonClick();

        BlockAll.blocksRaycasts = true;
        SceneManager.LoadScene("Map");
    }

    public void btnReplayClick()
    {
        AdsManager.Instance.ShowInterstitial();

        transform.SendMessage("StopTimer");
        SoundManager.Instance.Play_ButtonClick();
        BlockAll.blocksRaycasts = true;
        SceneManager.LoadScene("Room");
    }

    public void btnNextLevelClick()
    {
        AdsManager.Instance.ShowInterstitial();


        SoundManager.Instance.Play_ButtonClick();
        //GameData.UnlockLevel();
        GameData.CurrentLevel++;
        selectedRoom = GameData.CurrentLevel;

        BlockAll.blocksRaycasts = true;
        SceneManager.LoadScene("Room");
    }

    public void btnMenuClick()
    {
        SoundManager.Instance.Play_ButtonClick();
        bMoreOptionsMenu = !bMoreOptionsMenu;
        BtnMenuBG.rectTransform.localScale = new Vector3(-1 * BtnMenuBG.rectTransform.localScale.x, 1, 1);

        if (bMoreOptionsMenu) //  (BtnMenuBG.rectTransform.localScale.x <0)
        {
            animMoreOptionsMenu.ResetTrigger("tHide");
            animMoreOptionsMenu.SetTrigger("tShow");
            StopCoroutine("AutoHideMoreOptionsMenu");
            StartCoroutine("AutoHideMoreOptionsMenu");
        }
        else
        {
            animMoreOptionsMenu.ResetTrigger("tShow");
            animMoreOptionsMenu.SetTrigger("tHide");
            StopCoroutine("AutoHideMoreOptionsMenu");
        }

        //WebelinxCMS.Instance.IsInterstitialAvailable(WebelinxCMS.INTERSTITIAL_MENI_ID);
        //Debug.Log("MENI INTERSTITAL, ID=" +WebelinxCMS.INTERSTITIAL_MENI_ID);
    }

    IEnumerator AutoHideMoreOptionsMenu()
    {
        float waitingTime = 0;
        while (waitingTime < 5)
        {
            if (!bPause) waitingTime += 0.5f;
            yield return new WaitForSeconds(0.5f);
        }

        Debug.Log("HIDE MORE OPTIONS");

        animMoreOptionsMenu.ResetTrigger("tShow");
        animMoreOptionsMenu.SetTrigger("tHide");
        bMoreOptionsMenu = false;
        BtnMenuBG.rectTransform.localScale = Vector3.one;
    }


    IEnumerator SetBlockAll(float time, bool blockRays)
    {
        if (BlockAll == null) BlockAll = GameObject.Find("ForegroundBlockAll").GetComponent<CanvasGroup>();
        yield return new WaitForSeconds(time);
        BlockAll.blocksRaycasts = blockRays;
        BlockAll.alpha = blockRays ? 1 : 0;
    }


    //****************************************************
    void TaskCompleted(Vector3 itemPos)
    {
        SoundManager.Instance.Play_TaskCompleted();

        psController.ShootPS(itemPos, animTasks.transform.position);
        GameData.CompletedTasks++;

        if (GameData.CompletedTasks < GameData.TotalTasks)
        {
            animTasks.SetTrigger("tTaskCompleted");
        }
        else
        {
            GameData.CompletedTasks = GameData.TotalTasks;
            bPause = true;
            animTasks.SetTrigger("tAllTasksCompleted");
            StartCoroutine("End");
        }

        txtCompletedTasks.text = GameData.CompletedTasks.ToString();
    }


    public void ShowHint()
    {
        if (GameData.TimeLeft < 3)
        {
            return;
        }

        SoundManager.Instance.Play_ButtonClick();
        if (GameData.HintsLeft > 0 && !bHintActivated)
        {
            if (!Tutorial.bTutorial) GameData.HintsLeft--;
            else if (Tutorial.bTutorial && GameData.TutorialShown == 0)
            {
                if (Tutorial.TutorialPhase == 9) Tutorial.TutorialPhase = 10;
            }

            if (GameData.HintsLeft == 0)
            {
                btnHintsLeft.image.sprite = hintsLeft[0];
                imgHintsLeft.enabled = false;
                //WebelinxCMS.Instance.IsVideoRewardAvailable(WebelinxCMS.WATCH_VIDEO_ID);

                //StartCoroutine("SetBtnHintActive");
            }
            else
            {
                txtHintsLeft.text = GameData.HintsLeft.ToString();
                imgHintsLeft.sprite = hintsLeft[GameData.HintsLeft];
                //if(GameData.HintsLeft == 1) WebelinxCMS.Instance.IsVideoRewardAvailable(WebelinxCMS.WATCH_VIDEO_ID);
            }

            StopCoroutine("FadeInHint");
            StopCoroutine("FadeOutHint");
            bHintActivated = true;
            StartCoroutine("FadeInHint");
        }
        else if (GameData.HintsLeft == 0 && !bHintActivated &&
                 videoBonusHints < GameData.VideoHints) //&& GameData.bWatchVideoReady)
        {
            //bPause = true;
            menuWatchVideoName = "HintsButton";

            GameData.bWatchVideoStart = true;
            AdsManager.Instance.IsVideoRewardAvailable();

            //Debug.Log("WATCHING VIDEO, ID=" +WebelinxCMS.WATCH_VIDEO_ID);
            //BRISI
            //Debug.Log("BRISI FINISH WATCHING VIDEO HINT");
            //FinishWatchingVideoError();
            //FinishWatchingVideo();
        }
    }

    IEnumerator SetBtnHintActive()
    {
        yield return new WaitForSeconds(.5f);
        if (!GameData.bWatchVideoReady)
        {
            btnHintsLeft.interactable = false;
            btnHintsLeft.image.sprite = imgHintsLeftOff;
        }
    }

    IEnumerator FadeInHint()
    {
        BlockAll.blocksRaycasts = true;
        HintBg.gameObject.SetActive(true);
        float a = 1;
        //for (float a = 0; a<=1.05; a += 0.05f)
        //{
        foreach (SpriteRenderer sp in HintSprites)
        {
            sp.color = new Color(1, 1, 1, a);
        }

        HintBg.alpha = a;
        yield return new WaitForSeconds(0.02f);
        //	}

        StartCoroutine("FadeOutHint");
    }

    IEnumerator FadeOutHint()
    {
        yield return new WaitForSeconds(2);
        if (Tutorial.TutorialPhase == 10)
        {
            yield return new WaitForSeconds(2); //u tutuorijalu je hint duzi
        }

        if (bVideoBonusHintActivated)
        {
            yield return new WaitForSeconds(3); //posle videa je hint duzi
            bVideoBonusHintActivated = false;
            //bPause = false;
        }

        float a = 0;
        //for (float a = 1; a>-0.05f; a -= 0.05f)
        //{
        foreach (SpriteRenderer sp in HintSprites)
        {
            sp.color = new Color(1, 1, 1, a);
        }

        HintBg.alpha = a;
        yield return new WaitForSeconds(0.02f);
        //}

        yield return new WaitForSeconds(0.5f);
        HintBg.gameObject.SetActive(false);
        bHintActivated = false;
        BlockAll.blocksRaycasts = false;

        if (Tutorial.TutorialPhase == 10)
        {
            Tutorial.bTutorial = false;
            GameData.TuturialOver();
            Tutorial.TutorialPhase = 100;
        }
    }


    void FadeOutHint2()
    {
        foreach (SpriteRenderer sp in HintSprites)
        {
            sp.color = new Color(1, 1, 1, 0);
        }

        HintBg.alpha = 0;

        HintBg.gameObject.SetActive(false);
    }


    IEnumerator End()
    {
        transform.SendMessage("StopTimer");
        yield return new WaitForSeconds(1);
        if (GameData.CurrentLevel < 8)
        {
            menuManager.ShowPopUpMenu(PopUpLevelCompleted);
            GameData.UnlockLevel();
        }
        else
        {
            menuManager.ShowPopUpMenu(PopUpWIN);
        }
    }


    //WATCH VIDEO TIME MENI
    public void btnTimeNoThanksClick()
    {
        SoundManager.Instance.Play_ButtonClick();
        BlockAll.blocksRaycasts = true;
        menuManager.ClosePopUpMenu(PopUpWatchVideoForTime);
        StartCoroutine("TimeNoThanks");
    }

    IEnumerator TimeNoThanks()
    {
        menuManager.ClosePopUpMenu(PopUpWatchVideoForTime);
        transform.SendMessage("StopTimer");
        yield return new WaitForSeconds(0.5f);
        menuManager.ShowPopUpMenu(PopUpLevelFailed);
        //SceneManager.LoadScene("Home");
    }

    public void btnWatchVideoTime()
    {
        SoundManager.Instance.Play_ButtonClick();
        BlockAll.blocksRaycasts = true;

        menuWatchVideoName = "Time";

        GameData.bWatchVideoStart = true;
        AdsManager.Instance.IsVideoRewardAvailable();
        //WebelinxCMS.Instance.ShowVideoReward(WebelinxCMS.WATCH_VIDEO_ID);

        //BRISI
        //Debug.Log("BRISI FINISH WATCHING VIDEO TIME");
        //FinishWatchingVideoError();
        // FinishWatchingVideo( );
        StartCoroutine("ErrorWatchVideoUnblock");
    }

    IEnumerator ErrorWatchVideoUnblock()
    {
        yield return new WaitForSeconds(1f);
        BlockAll.blocksRaycasts = false;
    }


    public void FinishWatchingVideoError()
    {
        bPause = true;
        Debug.Log("ERROR " + menuWatchVideoName);


        if (menuWatchVideoName == "HintsButton")
        {
            //btnHintsLeft.interactable = false;
            //btnHintsLeft.image.sprite = imgHintsLeftOff;
            menuManager.ShowPopUpMessage("", "Video not available at the moment");
            menuWatchVideoName = "";
            StartCoroutine("CloseHintError");
        }

        if (menuWatchVideoName == "Time")
        {
            menuManager.ClosePopUpMenu(PopUpWatchVideoForTime);
            StartCoroutine("DelayErrorMessage");
        }
    }

    IEnumerator CloseHintError()
    {
        yield return new WaitForSeconds(2.5f);
        StartCoroutine(DelayPause());
        menuManager.ClosePopUpMenu(PopUpVideoNotAvailable);
    }


    IEnumerator DelayErrorMessage()
    {
        yield return new WaitForSeconds(0.5f);
        menuManager.ShowPopUpMessage("", "Video not available at the moment");
    }


    public void FinishWatchingVideo()
    {
        Debug.Log("GOTOV VIDEO");

        if (menuWatchVideoName == "HintsButton")
        {
            videoBonusHints++;
            if (videoBonusHints >= GameData.VideoHints)
            {
                btnHintsLeft.interactable = false;
                btnHintsLeft.image.sprite = imgHintsLeftOff;
            }

            StartCoroutine(DelayPause()); //bPause = false;
            Debug.Log("VIDEO");
            StopCoroutine("FadeInHint");
            StopCoroutine("FadeOutHint");
            bHintActivated = true;
            bVideoBonusHintActivated = true;
            //bPause = true;
            StartCoroutine("FadeInHint");
        }
        else if (menuWatchVideoName == "Time")
        {
            StartCoroutine(DelayPause()); //bPause = false;
            GameData.TimeLeft = GameData.VideoBonusTime;
            GameData.bOutOfTime = false;
            menuManager.ClosePopUpMenu(PopUpWatchVideoForTime);
        }

        menuWatchVideoName = "";
    }

    public void btnClosePopUpVideoNotAvailable()
    {
        StopCoroutine("CloseHintError");
        SoundManager.Instance.Play_ButtonClick();
        StartCoroutine(DelayPause()); //bPause = false;
        menuManager.ClosePopUpMenu(PopUpVideoNotAvailable);

        if (menuWatchVideoName == "Time")
        {
            StartCoroutine("TimeNoThanks");
            menuWatchVideoName = "";
        }
    }

    public void OutOfTime()
    {
        bPause = true;
        if (GameData.bWatchVideoReady && videoBonusTime == 0)
        {
            menuManager.ShowPopUpMenu(PopUpWatchVideoForTime);
            videoBonusTime++;
        }
        else
        {
            menuManager.ShowPopUpMenu(PopUpLevelFailed);
        }
    }

    IEnumerator DelayPause()
    {
        yield return new WaitForSeconds(0.7f);
        bPause = false;
    }

    public void ClickSound()
    {
        SoundManager.Instance.Play_ButtonClick();
    }
}
